package com.example.demo.service.impl;

import com.example.demo.bean.Category;
import com.example.demo.dao.CategoryMapper;
import com.example.demo.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public List<Category> queryCategory() {
        List<Category> list = categoryMapper.queryCategory();
        List<Category> parents = new ArrayList<>();
        List<Category> categorieTree = new ArrayList<>();
        for(Category category : list){
            if(category.getPid() == 0){
                parents.add(category);
            }
        }
        for(Category parent : parents){
            List<Category> children = new ArrayList<>();
            for(Category child : list ){
                if(parent.getId() == child.getPid()){
                    children.add(child);
                }
            }
            parent.setChildList(children);
            categorieTree.add(parent);
        }
        return categorieTree;
    }
}
